<?php
error_reporting(0);
define('IN_QY', true);
session_start();
require("include/common.inc.php");
//$_COOKIE['userid'] = '151202424559';
//$_COOKIE['username'] = '13013679550';
if($_COOKIE['userid']){
    $user_id = $_COOKIE['userid'];
}elseif ($_GET['userid']){
    $user_id = $_GET['userid'];
}else{
    $user_id = '';
}


if (!$user_id) {
    echo "<script type='text/javascript'>alert('请先登录！');location.href='mlogin.php';</script>";
    exit;
}
$today = date("Y-m-d");
$yestoday = date("Y-m-d", strtotime("-1 day"));

// 同步tbl_zhangdan中的签到日期到tbl_month_sign
$y_re = c_getRows("select time from tbl_zhangdan WHERE title = '网站登录' AND by2=2 AND username = ".$user_id);
$p_re = c_getRow("select id from tbl_month_sign WHERE user_id = ".$user_id);
if($y_re){
    $count_arr = '';
    foreach ($y_re as $t){
        $count_arr[] = date('Y-m-d',strtotime($t['time']));
    }
    $signHistoy = implode(',',array_unique($count_arr));

    if($p_re){
        $res = c_update(['signHistoy' => $signHistoy], 'tbl_month_sign', "user_id = " .$user_id);
    }else{
        $res = c_insert(['user_id' => $user_id, 'signcount' => 1, 'count' => 1, 'lastModifyTime' => $today, 'signHistoy' => $today], 'tbl_month_sign');
    }
}

$re_info = c_getRow("select id,signcount,`count`,signHistoy,lastModifyTime from tbl_month_sign WHERE user_id = " . $user_id);
$l_count = $re_info['count'] ? $re_info['count'] : 0;
// 用原来的登录次数统计
$contem = "网站登录";
$sql = "select count(*) as daynum from tbl_zhangdan where username='".$user_id."' and title='".$contem."' and by2=2";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
$l_count = $row['daynum'];

$l_signHistoy = isset($re_info['signHistoy']) ? $re_info['signHistoy'] : 0;
if ($re_info) {
    if ($re_info['lastModifyTime'] < $yestoday) {
        $res = c_update(['signcount' => 0], 'tbl_month_sign', "user_id = " . $user_id);
    }
}
$l_signcount = $re_info['signcount'] ? $re_info['signcount'] : 0; // 连续签到
$day_info = c_getRow("select id from tbl_month_sign WHERE user_id = " . $user_id . " and find_in_set('$today',signHistoy)  ");
if ($re_info) {
    // 本月签到情况
    if ($re_info['signHistoy']) {
        $all_days = get_month_all_days(date("Y-m"));
        $ex_days = array_intersect($all_days, explode(',', $re_info['signHistoy']));
        foreach ($ex_days as $day) {
            $d = date('d', strtotime($day));
            if (substr($d, 0, 1) == '0') {
                $d = substr($d, 1, 1);
            }
            $aleady_sign_days .= $d . ',';
        }
        $aleady_sign_days = rtrim($aleady_sign_days, ",");
    } else {
        $aleady_sign_days = '';
    }
} else {
    $aleady_sign_days = '';
}

// 查询某个月签到情况
function singin_detail_month($month,$user_id){
    $aleady_sign_days = '';
    $re_info = c_getRow("select id,signcount,`count`,signHistoy,lastModifyTime from tbl_month_sign WHERE user_id = " . $user_id);
    if ($re_info) {
        // 本月签到情况
        if ($re_info['signHistoy']) {
            $all_days = get_month_all_days(date("Y-m",strtotime($month)));
            $ex_days = array_intersect($all_days, explode(',', $re_info['signHistoy']));
            foreach ($ex_days as $day) {
                $d = date('d', strtotime($day));
                if (substr($d, 0, 1) == '0') {
                    $d = substr($d, 1, 1);
                }
                $aleady_sign_days .= $d . ',';
            }
            $aleady_sign_days = rtrim($aleady_sign_days, ",");
        } else {
            $aleady_sign_days = '';
        }
    } else {
        $aleady_sign_days = '';
    }
    return $aleady_sign_days;
}

// 签到
function singin_func($user_id){
    $now = date("Y-m-d",time());
    $sql = "select * from tbl_zhangdan where id=".$user_id ." and date_format(time,'%Y-%m-%d') = '$now'  AND title = '网站登录'  ";
    $query = mysql_query($sql);
    $res = mysql_fetch_array($query);
    $lastlogin = $res['time'];
    //判断是否当日第一次登陆
    $rtime = date("Y-m-d h:i:s",time());
    $ptime = date("Y-m-d",strtotime($rtime));
    $latesttime = date("Y-m-d",strtotime($lastlogin));
    if ($ptime != $latesttime) {
        //加积分
		        //进账单
        $sqlu = "select * from tbl_user where id=".$user_id;
        $queryu=mysql_query($sqlu);
        $rowu=mysql_fetch_array($queryu);
        $jifen = $rowu['jifen'];
        $yuee = $rowu['yuee'];
        $xyf = $rowu['xyf'];
        $vip = $rowu['vip'];
        $yuid = $rowu['id'];
		        //送积分
		if($rowu['viplevel']==2){
	     $sql_jf = "update tbl_user set jifen=jifen+2,xyf=xyf+1 where id ='".$user_id."' or shuyu ='".$_COOKIE['shuyu']."'";
        mysql_query($sql_jf);
		
        $sqly = "insert into tbl_zhangdan values (0,'网站登录','2','".$jifen."','".$xyf."',1,'".$yuee."','".date('Y-m-d H:i:s')."','".$yuid."',0,0,2)";
        $r1 = mysql_query($sqly);	
		
		}else{
			
		$sql_jf = "update tbl_user set jifen=jifen+1,xyf=xyf+1 where id ='".$user_id."' or shuyu ='".$_COOKIE['shuyu']."'";
        mysql_query($sql_jf);
		
        $sqly = "insert into tbl_zhangdan values (0,'网站登录','1','".$jifen."','".$xyf."',1,'".$yuee."','".date('Y-m-d H:i:s')."','".$yuid."',0,0,2)";
        $r1 = mysql_query($sqly);	
			
			
		}
		

        //送信用
        $sqlyu = "insert into tbl_zhangdan values (0,'签到送信用','1','".$jifen."','".$xyf."',1,'".$yuee."','".date('Y-m-d H:i:s')."','".$yuid."',0,0,1)";
        $r2 = mysql_query($sqlyu);
    }

    $sql = "update tbl_user set beizhu1='".$rtime."' where id ='".$user_id."' or shuyu ='".$_COOKIE['shuyu']."'";

    //结束
    mysql_query($sql);
}

function get_month_all_days($f_date)
{
    $j = date("t", strtotime($f_date));
//    $j = date("t"); //获取当前月份天数
    $start_time = strtotime($f_date.'-01');  //获取某月第一天时间戳
    $array = array();
    for ($i = 0; $i < $j; $i++) {
        $array[] = date('Y-m-d', $start_time + $i * 86400); //每隔一天赋值给数组
    }
    return $array;
}

if (isset($_POST['action'])) {
    if ($_POST['action'] == 'add') {
        // 签到
        if ($day_info) {
            // 今天已经签到
            echo json_encode(["code" => 0, "msg" => "已签到"]);
            exit();
        } else {
            if (!$re_info) {
                singin_func($user_id); // 签到
                $res = c_insert(['user_id' => $user_id, 'signcount' => 1, 'count' => 1, 'lastModifyTime' => $today, 'signHistoy' => $today], 'tbl_month_sign');
            } else {
                $signHistoy = $re_info['signHistoy'] . ',' . $today;
                $signcount = $re_info['signcount'] + 1; // 连续签到
                $count = $re_info['count'] + 1;
                singin_func($user_id); // 签到
                $res = c_update(['signcount' => $signcount, 'count' => $count, 'lastModifyTime' => $today, 'signHistoy' => $signHistoy], 'tbl_month_sign', "user_id = " . $_COOKIE['userid']);
            }
            if ($res) {
                echo json_encode(["code" => 1, "msg" => "签到成功"]);
                exit();
            } else {
                echo json_encode(["code" => 0, "msg" => "签到失败"]);
                exit();
            }

        }
    }
    // 翻页
    if($_POST['action'] == 'cx_month'){
        $month = $_POST['month'];
        $data = singin_detail_month($month,$user_id);
        echo json_encode(["code" => 1, "data" => $data]);
        exit();
    }

}

?>

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no">
    <title>签到</title>
    <link rel="stylesheet" href="/ui/qiandaonew/css/public.css"/>
    <link rel="stylesheet" href="/ui/qiandaonew/css/signin.css"/>
<link rel="stylesheet" href="/ui/fontt/css/font-awesome.min.css">	
	<style>
.am-header {
    position: relative;
    width: 100%;
    height: 49px;
    line-height: 49px;
    padding: 0 10px;
}
.dream-head {
    filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr='#9400d4',endColorStr='#d644b2',gradientType='1');
    background: -moz-linear-gradient(left, #9400d4, #d644b2);
    background: -o-linear-gradient(left,#9400d4, #d644b2);
    background: -webkit-gradient(linear, 0% 0%, 100% 0%, from(#ff9800), to(#d644b2));
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
}	
.am-header-default .am-header-nav {
    color: #eee;
}
.am-header .am-header-left {
    left: 10px;
}
.am-header .am-header-nav {
    position: absolute;
    top: 0;
}
.am-header-default .am-header-title, .am-header-default .am-header-title a {
    color: #fff;
    font-size: 21px;	
}
.am-header .am-header-title {
    margin: 0 30%;
    font-weight: 400;
    text-align: center;
    display: block;
    word-wrap: normal;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

.am-header h1 {
    margin-top: 0;
    margin-bottom: 0;
}
*+h1, *+h2, *+h3, *+h4, *+h5, *+h6 {
    margin-top: 2em;
}
h1 {
    font-size: 1.5em;
}
h1, h2, h3, h4, h5, h6 {
    margin: 0 0 1.6rem;
    font-weight: 600;
    font-size: 100%;
}
*, :after, :before {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
	</style>
</head>

<body>

<header data-am-widget="header" class="am-header am-header-default dream-head  am-no-layout">
			<div class="am-header-left am-header-nav">
				<a href="javascript:;" onclick="goback()" class="">
				<i class="fa fa-chevron-left fa-lg" style="color:white;"></i>
				</a>
			</div>
			<h1 class="am-header-title">
  	            <a href="" class="">签到</a>
            </h1>
</header>

<div class="top flex flex-align-end flex-pack-center flex-warp">
    <div class="out-1 flex flex-align-center flex-pack-center" id="signIn">
        <div class="out-2 flex flex-align-center flex-pack-center">
            <div class="signBtn">
                <strong id="sign-txt"><? $day_info ? $p_re = '已签到' : $p_re = '签到';
                    echo $p_re; ?></strong>
                <span>已签到<em id="sign-count"><? echo $l_count; ?></em>天</span>
            </div>
        </div>
    </div>
</div>
    <?php
    $sql = "select jifen from tbl_user where id=".$_COOKIE['userid'];
    $jifen = c_getRow($sql)['jifen'];

    ?>
<!--<div class="tips">今天已签到，获得1个红包</div>-->
<div class="tips" style="top:13rem;">总积分:<?= $jifen ?> &nbsp;<a href="jf.php" style="border: 1px solid #f5f2f1;border-radius: 10px; padding: 3px;color: white;"> 积分中心</a></div>
<div class="Calendar">
    <div id="toyear" class="flex flex-pack-center">
        <div id="idCalendarPre" style="">&lt;</div>
        <div class="year-month">
            <span id="idCalendarYear">2018</span>年<span id="idCalendarMonth">6</span>月
        </div>
        <div id="idCalendarNext" style="">&gt;</div>
    </div>
    <table border="1px" cellpadding="0" cellspacing="0">
        <thead>
        <tr class="tou">
            <td>日</td>
            <td>一</td>
            <td>二</td>
            <td>三</td>
            <td>四</td>
            <td>五</td>
            <td>六</td>
        </tr>
        </thead>
        <tbody id="idCalendar">
        </tbody>
    </table>
</div>
<script type="text/javascript" src="/ui/qiandaonew/js/rili.js"></script>
<script type="text/javascript" src="/ui/qiandaonew/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="/ui/layer/mobile/layer.js"></script>   
<script language="JavaScript">
    var isSign = false;
    var myday = new Array(); //已签到的数组
    //			myday[0] = "1528646400"
    //			myday[1] = "1528387200"
    //			myday[2] = "1525708800"

    var cale = new Calendar("idCalendar", {
        qdDay: myday,
        onToday: function (o) {
            o.className = "onToday";
        },
        onSignIn: function () {
            $$("sign-txt").innerHTML = '已签到';
        },
        onFinish: function () {
            $$("sign-count").innerHTML = <? echo $l_count; ?> //已签到次数
            $$("idCalendarYear").innerHTML = this.Year;
            $$("idCalendarMonth").innerHTML = this.Month; //表头年份

        }
    });
    $$("idCalendarPre").onclick = function () {
        cale.PreMonth();
        var month = $("#idCalendarYear").text()+"-"+$("#idCalendarMonth").text();
        // 变色查询
        $.ajax({
            type: "POST",
            url: "qiandao.php",
            dataType: "json",
            data: {'action': 'cx_month','month':month},
            async: false,
            success: function (data) {
                if (data.code == 1) {
                    var aleady_sign_days = (data.data)
                    // 已经签到的变色
                    var aleady_sign_days_arr = aleady_sign_days.split(',');
                    $("#idCalendar").find("td").each(function () {
                        var tday = $(this).children("span").text();
                        var index = $.inArray(tday, aleady_sign_days_arr);
                        if (index >= 0) {
                            $(this).addClass('onToday');
                        }
                    })
                }
            }
        });
    }
    $$("idCalendarNext").onclick = function () {
        cale.NextMonth();
        var month = $("#idCalendarYear").text()+"-"+$("#idCalendarMonth").text();
        // 变色查询
        $.ajax({
            type: "POST",
            url: "qiandao.php",
            dataType: "json",
            data: {'action': 'cx_month','month':month},
            async: false,
            success: function (data) {
                if (data.code == 1) {
                    var aleady_sign_days = (data.data)
                    // 已经签到的变色
                    var aleady_sign_days_arr = aleady_sign_days.split(',');
                    $("#idCalendar").find("td").each(function () {
                        var tday = $(this).children("span").text();
                        var index = $.inArray(tday, aleady_sign_days_arr);
                        if (index >= 0) {
                            $(this).addClass('onToday');
                        }
                    })
                }
            }
        });
    }

    //添加今天签到
    $$("signIn").onclick = function () {
        if (isSign == false) {
            var res = cale.SignIn();
            // 签到查询
            $.ajax({
                type: "POST",
                url: "qiandao.php",
                dataType: "json",
                data: {'action': 'add'},
                async: false,
                success: function (data) {
                    if (data.code == 0) {
                        alert(data.msg);
                    } else if (data.code == 1) {
                        if (res == '1') {
                            $$("sign-txt").innerHTML = '已签到';
                            $$("sign-count").innerHTML = parseInt($$("sign-count").innerHTML) + 1;
                            isSign = true;
                        } else if (res == '2') {
                            $$("sign-txt").innerHTML = '已签到';
							  layer.open({
                               content: '今天已经签到了'
                                 ,skin: 'msg'
                                 ,time: 2 
                                   });
                        }
                    }

                }
            });

        } else {
  layer.open({
    content: '今天已经签到了'
    ,skin: 'msg'
    ,time: 2 //2秒后自动关闭
  });
        }

    }
	
	
	
	
	
	
</script>
<script>
           zouni();
      function zouni() {
        if (isSign == false) {
            var res = cale.SignIn();
            // 签到查询
            $.ajax({
                type: "POST",
                url: "qiandao.php",
                dataType: "json",
                data: {'action': 'add'},
                async: false,
                success: function (data) {
                    if (data.code == 0) {
						
						
                       
						
								layer.open({
                               content: data.msg
                                 ,skin: 'msg'
                                 ,time: 2 
                                   });
						
						
                    } else if (data.code == 1) {
                        if (res == '1') {
                            $$("sign-txt").innerHTML = '已签到';
                            $$("sign-count").innerHTML = parseInt($$("sign-count").innerHTML) + 1;
                            isSign = true;
                        } else if (res == '2') {
                            $$("sign-txt").innerHTML = '已签到';
							  layer.open({
                               content: '今天已经签到了'
                                 ,skin: 'msg'
                                 ,time: 2 
                                   });
                        }
                    }

                }
            });

        } else {
  layer.open({
    content: '今天已经签到了'
    ,skin: 'msg'
    ,time: 2 //2秒后自动关闭
  });
        }

    }
	




</script>
<script>
    var aleady_sign_days = '<?php echo $aleady_sign_days; ?>';
    if (aleady_sign_days != '') {
        // 已经签到的变色
        aleady_sign_days_arr = aleady_sign_days.split(',');
        $("#idCalendar").find("td").each(function () {
            var tday = $(this).children("span").text();
            var index = $.inArray(tday, aleady_sign_days_arr);
            if (index >= 0) {
                $(this).addClass('onToday');
            }
        })
    }
</script>


<script>


function goback(){
   window.location.href=document.referrer;		
}

</script>
</body>

</html>